package ace.cmp.data.methodname.sql.mybatisplus.core.mysql.dml;

import ace.cmp.data.methodname.method.name.sql.core.enums.SqlCommandTypeEnum;
import ace.cmp.data.methodname.method.name.sql.entity.model.EntityMethodNameToQueryFilter;
import ace.cmp.data.methodname.method.name.sql.entity.resolver.EntityMethodNameToQueryResolver;
import ace.cmp.data.methodname.sql.mybatisplus.core.mysql.dml.exception.DeleteDmlNotSupportNoFilterException;
import ace.cmp.data.methodname.sql.mybatisplus.core.properties.MybatisPlugMethodNameToSqlProperties;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import java.util.List;
import org.apache.ibatis.jdbc.SQL;

/**
 * @author caspar
 * @date 2023/2/24 9:05 mybatis plus 根据method推导sql
 */
public class MethodToSqlDeleteMysqlBuilder extends AbstractMethodToDmlSqlBuilder {

  public MethodToSqlDeleteMysqlBuilder(
      EntityMethodNameToQueryResolver queryResolver,
      TableInfo tableInfo,
      MybatisPlugMethodNameToSqlProperties sqlProperties) {
    super(queryResolver, tableInfo, sqlProperties);
  }

  @Override
  public String getSql() {
    SQL sqlBuilder = this.getSqlBuilder();
    sqlBuilder.DELETE_FROM(this.getTableInfo().getTableName());
    this.addFilters();
    this.addLimit();
    return this.getSqlBuilder().toString();
  }

  @Override
  public Boolean getSupport() {
    return SqlCommandTypeEnum.DELETE.equals(getQueryResolver().getSqlCommandType());
  }

  @Override
  protected void addFilters() {
    List<EntityMethodNameToQueryFilter> queryFilters = this.getQueryResolver().getFilters();
    if (queryFilters.size() == 0
        && Boolean.TRUE.equals(this.getSqlProperties().getDeleteWhereCheck())) {
      throw new DeleteDmlNotSupportNoFilterException(
          String.format(
              "method %s delete dml must has at least one filter",
              this.getQueryResolver().getMethod().getName()));
    }
    super.addFilters();
  }
}
